<script setup lang='ts'>
import { FormItemProps, FormRule } from 'tdesign-vue-next';
import { PropType, ref, watch } from 'vue';

const props = defineProps({
    modelValue: {
        type: [String, Array],
        default: '',
        require: true
    },
    placeholder: {
        type: String,
        default: '请输入内容'
    },
    name: {
        type: String,
        default: '',
        require: true
    },
    label: {
        type: String,
        default: ''
    },
    formAttrs: {
        type: <PropType<FormItemProps>>Object,
        default: () => ({})
    },
    readonly: {
        type: Boolean,
        default: false
    },
    disabled: {
        type: Boolean,
        default: false
    },
    rules: {
        type: Array<FormRule>,
        default: () => []
    },
    range: {
        type: Boolean,
        default: false
    },
    format: {
        type: String,
        default: 'YYYY-MM-DD'
    },
    help: {
        type: String,
        default: ''
    },
    enableTimePicker: {
        type: Boolean,
        default: false
    }
});

const emits = defineEmits<{
    (e: 'update:modelValue', value: any): void;
    (e: 'change', value: any): void;
}>();

const innerValue = ref<any>(props.modelValue);

watch(() => props.modelValue, (val) => {
    innerValue.value = val;
})

function handleChange(value: any, context: any) {
    emits('update:modelValue', value)
    emits('change', { value, context })
}

</script>

<template>
    <t-form-item :help="props.help" v-bind="props.formAttrs" :rules="props.rules" :name="name" :label="label">
        <t-date-picker :enable-time-picker="enableTimePicker" style="width: 100%"
            :disabled="props.disabled || props.readonly" :format="props.format" @change="handleChange" v-if="!props.range"
            v-bind="$attrs" v-model="innerValue" />
        <t-date-range-picker :enable-time-picker="enableTimePicker" :disabled="props.disabled || props.readonly" v-else
            v-bind="$attrs" v-model="innerValue" @change="handleChange" />
    </t-form-item>
</template>

<style scoped></style>